<template>
  <view class="content" style="background: transparent;">
    <view class="bott-btn">
      <button type="primary" @click="handleClick">确认</button>
    </view>
    <view class="phxx-item-detail">
      <view class="content-box">
        <view class="bottom block-back">
          <view class="uni-form-item">
            <view class="title"><span style="color:red;">*</span>地址类型</view>
            <view class="uni-select-box">
              <picker :disabled="isEdit" @change="changeAdress" :value="itemList.siteType" mode="selector"
                :range="adressRange" range-key="text">
                <view class="uni-input">{{siteTypeName || ''}}</view>
              </picker>
              <uni-icons type="forward" size="20"></uni-icons>
            </view>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color:red;">*</span>地址名称</view>
            <input class="uni-input" v-model="itemList.siteName" :disabled="isEdit" />
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color:red;">*</span>省</view>
            <view class="uni-select-box">
              <picker :disabled="isEdit" @change="changeProvince" :value="itemList.province" mode="selector"
                :range="provinceLists" range-key="text">
                <view class="uni-input">{{itemList.provinceName || ''}}</view>
              </picker>
              <uni-icons type="forward" size="20"></uni-icons>
            </view>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color:red;">*</span>市</view>
            <view class="uni-select-box">
              <picker :disabled="isEdit" @change="changeCity" :value="itemList.city" mode="selector" :range="cityLists"
                range-key="text">
                <view class="uni-input">{{itemList.cityName || ''}}</view>
              </picker>
              <uni-icons type="forward" size="20"></uni-icons>
            </view>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color:red;">*</span>区县</view>
            <view class="uni-select-box">
              <picker :disabled="isEdit" @change="changeCuontry" :value="itemList.county" mode="selector"
                :range="cuontryLists" range-key="text">
                <view class="uni-input">{{itemList.countyName || ''}}</view>
              </picker>
              <uni-icons type="forward" size="20"></uni-icons>
            </view>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color:red;">*</span>街道</view>
            <view class="uni-select-box">
              <picker :disabled="isEdit" @change="changeTown" :value="itemList.town" mode="selector" :range="townLists"
                range-key="text">
                <view class="uni-input">{{itemList.townName || ''}}</view>
              </picker>
              <uni-icons type="forward" size="20"></uni-icons>
            </view>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color:red;">*</span>详细地址</view>
            <input class="uni-input" v-model="itemList.address" :disabled="isEdit" />
          </view>

        </view>

      </view>
    </view>
  </view>
</template>

<script>
  import { toast } from '@/utils/common';
  import { createOne, getOne, updateOne, getAreaTreesBycode } from '@/api/address.js';
  export default {
    driverName: 'resetPwd',
    props: {
    },
    data() {
      return {
        siteTypeName: '',
        searchData: {
          lat: '',
          lon: ''
        },
        address: '',
        adressRange: [{
          "value": 1,
          "text": "装货地",
        },
        {
          "value": 2,
          "text": "卸货地"
        }
        ],
        itemList: {
          id: undefined,
          siteType: undefined,
          siteName: undefined,
          province: undefined,
          provinceName: undefined,
          city: undefined,
          cityName: undefined,
          county: undefined,
          countyName: undefined,
          town: undefined,
          townName: undefined,
          address: undefined,
          lonLat: undefined
        },
        totalSeconds: 60,
        provinceLists: [],
        cityLists: [],
        cuontryLists: [],
        townLists: [],
        tempDatas: {},
        isEdit: false,
        fromMap: false,
        ifFirstEdit: true,
        isEditType: 'add'
      };
    },
    onLoad(options) {
      this.fromMap = false
      if (!!options) {
        this.isEdit = true
        if (!!options.id) {
          this.isEditType = "update"
          this.getDetail(options.id)
        }
        else this.isEdit = false
      }
      if (!this.isEdit) {
        uni.setNavigationBarTitle({
          title: '添加地址'
        });
      } else {
        uni.setNavigationBarTitle({
          title: '编辑地址'
        });
      }
      this.getProvinces()
    },
    watch: {
      'itemList.province': function (newVal, oldVal) {
        if (!this.isEdit) {
          this.itemList.city = undefined
          this.itemList.county = undefined
          this.itemList.town = undefined
          this.itemList.cityName = undefined
          this.itemList.countyName = undefined
          this.itemList.townName = undefined
        }
        if (!!newVal) this.getCitys(newVal)
      },
      'itemList.city': function (newVal, oldVal) {
        if (!this.isEdit) {
          this.itemList.county = undefined
          this.itemList.town = undefined
          this.itemList.countyName = undefined
          this.itemList.townName = undefined
        }
        if (!!newVal) this.getCountys(newVal)
      },
      'itemList.county': function (newVal, oldVal) {
        if (!this.isEdit) {
          this.itemList.town = undefined
          this.itemList.townName = undefined
        }
        this.isEdit = false
        if (!!newVal) this.getTowns(newVal)
      }
    },
    methods: {
      async getDetail(id) {
        let data = await getOne(id)
        let _ = this
        if (data.code == 0) {
          _.tempDatas = data.data
          _.itemList.id = data.data.id
          _.itemList.siteName = data.data.siteName
          _.itemList.siteType = data.data.siteType

          if (_.adressRange.length > 0) {
            _.adressRange.forEach(item => {
              if (item.value == data.data.siteType) _.siteTypeName = item.text
            })
          }
          _.itemList.address = data.data.address
          _.itemList.province = data.data.province
          _.itemList.provinceName = data.data.provinceName
          _.itemList.city = data.data.city
          _.itemList.cityName = data.data.cityName

          _.itemList.county = data.data.county
          _.itemList.countyName = data.data.countyName
          _.itemList.town = data.data.town
          _.itemList.townName = data.data.townName
        }
      },
      async getProvinces() {
        let data = await getAreaTreesBycode(0)

        if (!!data) {
          if (!!data.data && data.data.length > 0) {
            this.provinceLists = []
            data.data.forEach(item => {
              this.provinceLists.push({
                value: item.code,
                text: item.name
              })
            })
          }
        }
      },
      async getCitys(id) {
        let data = await getAreaTreesBycode(id)
        if (!!data && data.data.length > 0) {
          this.cityLists = []
          data.data.forEach(item => {
            this.cityLists.push({
              value: item.code,
              text: item.name
            })
          })
          // if(this.isEdit) this.itemList.city = this.tempDatas.city
        }
      },
      async getCountys(id) {
        let data = await getAreaTreesBycode(id)
        if (!!data && data.data.length > 0) {
          this.cuontryLists = []
          data.data.forEach(item => {
            this.cuontryLists.push({
              value: item.code,
              text: item.name
            })
          })
          // if(this.isEdit) this.itemList.county = this.tempDatas.county
        }
      },
      async getTowns(id) {
        let data = await getAreaTreesBycode(id)
        if (!!data && data.data.length > 0) {
          this.townLists = []
          data.data.forEach(item => {
            this.townLists.push({
              value: item.code,
              text: item.name
            })
          })
          // if(this.isEdit) this.itemList.town = this.tempDatas.town
        }
      },
      changeProvince(e) {
        this.ifFirstEdit = false
        if (this.provinceLists.length > 0) {
          this.itemList.provinceName = this.provinceLists[e.detail.value].text
          this.itemList.province = this.provinceLists[e.detail.value].value
        }
        if (!this.isEdit) {
          this.itemList.city = undefined
          this.itemList.county = undefined
          this.itemList.town = undefined
          this.itemList.cityName = undefined
          this.itemList.countyName = undefined
          this.itemList.townName = undefined
        }
        if (!!this.provinceLists[e.detail.value].value) this.getCitys(this.provinceLists[e.detail.value].value)
      },
      changeCity(e) {
        this.ifFirstEdit = false
        this.itemList.city = e
        if (this.cityLists.length > 0) {
          this.itemList.cityName = this.cityLists[e.detail.value].text
          this.itemList.city = this.cityLists[e.detail.value].value
        }
        if (!this.isEdit) {
          this.itemList.county = undefined
          this.itemList.town = undefined
          this.itemList.countyName = undefined
          this.itemList.townName = undefined
        }
        if (!!this.cityLists[e.detail.value].value) this.getCountys(this.cityLists[e.detail.value].value)
      },
      changeCuontry(e) {
        this.ifFirstEdit = false
        if (this.cuontryLists.length > 0) {
          this.itemList.countyName = this.cuontryLists[e.detail.value].text
          this.itemList.county = this.cuontryLists[e.detail.value].value
        }
        if (!this.isEdit) {
          this.itemList.town = undefined
          this.itemList.townName = undefined
        }
        this.isEdit = false
        if (!!this.cuontryLists[e.detail.value].value) this.getTowns(this.cuontryLists[e.detail.value].value)
      },
      changeTown(e) {
        this.ifFirstEdit = false
        if (this.townLists.length > 0) {
          this.itemList.townName = this.townLists[e.detail.value].text
          this.itemList.town = this.townLists[e.detail.value].value
        }
        if (!this.fromMap) this.itemList.address = this.itemList.provinceName + this.itemList.cityName + this.itemList.countyName + this.itemList.townName
      },
      changeAdress(e) {
        if (this.adressRange.length > 0) {
          this.itemList.supplierName = this.adressRange[e.detail.value].text
          this.siteTypeName = this.adressRange[e.detail.value].text
          this.itemList.siteType = this.adressRange[e.detail.value].value
        }
      },
      chooseAdress() {
        let _this = this
        wx.chooseLocation({
          success: (res) => {
            console.log(res, '这是获取到的地理位置')
            this.itemList.province = undefined
            this.itemList.provinceName = undefined
            this.itemList.city = undefined
            this.itemList.county = undefined
            this.itemList.town = undefined
            this.itemList.cityName = undefined
            this.itemList.countyName = undefined
            this.itemList.townName = undefined
            this.itemList.address = res.address
            this.fromMap = true
          },
          fail: (err) => {
            console.log(err);
          }
        });
      },
      async handleClick() {
        let data = {}
        let _ = this
        if (!_.itemList.siteType) {
          toast(`请选择装货地类型`);
          return
        }
        if (!_.itemList.siteName) {
          toast(`地址名称不能为空`);
          return
        }
        if (!_.itemList.provinceName) {
          toast(`省不能为空`);
          return
        }
        if (!_.itemList.cityName) {
          toast(`市不能为空`);
          return
        }
        if (!_.itemList.countyName) {
          toast(`区县不能为空`);
          return
        }
        if (!_.itemList.townName) {
          toast(`街道不能为空`);
          return
        }
        if (!_.itemList.address) {
          toast(`详细地址不能为空`);
          return
        }
        let msg = ""
        if (this.isEditType == 'update') {
          msg = "编辑"
          data = await updateOne(this.itemList)
        } else {
          msg = "添加"
          data = await createOne(this.itemList)
        }
        if (data.code == 0) {
          uni.showToast({
            title: msg + '成功',
            icon: 'success'
          });
          uni.navigateBack({
            delta: 1
          });
        } else {
          toast(data.msg)
        }
      },
      parseTime(time, pattern) {
        if (arguments.length === 0 || !time) {
          return null;
        }
        const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
        let date;
        if (typeof time === 'object') {
          date = time;
        } else {
          if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
            time = parseInt(time);
          } else if (typeof time === 'string') {
            time = time
              .replace(new RegExp(/-/gm), '/')
              .replace('T', ' ')
              .replace(new RegExp(/\.[\d]{3}/gm), '');
          }
          if (typeof time === 'number' && time.toString().length === 10) {
            time = time * 1000;
          }
          date = new Date(time);
        }
        const formatObj = {
          y: date.getFullYear(),
          m: date.getMonth() + 1,
          d: date.getDate(),
          h: date.getHours(),
          i: date.getMinutes(),
          s: date.getSeconds(),
          a: date.getDay()
        };
        const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
          let value = formatObj[key];
          // Note: getDay() returns 0 on Sunday
          if (key === 'a') {
            return ['日', '一', '二', '三', '四', '五', '六'][value];
          }
          if (result.length > 0 && value < 10) {
            value = '0' + value;
          }
          return value || 0;
        });
        return time_str;
      }
    }
  };
</script>

<style lang="scss" scoped>
  button {
    font-size: 30.22rpx !important;
    background: #409eff !important;
    color: #fff !important;
  }

  .uni-form-item {
    border-bottom: 1px solid #E6E6E6;
    display: flex;
    justify-content: space-between;
    line-height: 100rpx;
    height: 100rpx;
    color: #333;

    .title {
      width: 185rpx;
    }

    .uni-input {
      flex: 3;
      border: 1px solid #fff;
      height: 70rpx;
      line-height: 70rpx;
      border-radius: 10rpx;
      padding: 0 10rpx;
      background-color: #fff;
      bottom: -14rpx;
      position: relative;
    }

    .uni-select-box {
      width: calc(100% - 186rpx);
      display: flex;
      justify-content: space-between;
      background: #fff;

      picker {
        width: 100%;
      }
    }
  }

  .phxx-item-detail {
    box-sizing: border-box;
    font-size: 14px;
    color: #000;
    margin: 20rpx;

    .content-box {
      .bottom {
        padding: 20rpx;
        font-size: 26.66rpx;
      }

      .btns {
        position: fixed;
        bottom: 0;
        height: 150rpx;
        width: 100%;
        margin: auto;
        z-index: 99;
        left: 0;
        right: 0;
        padding: 20rpx;
        background-color: #fff;
      }
    }
  }

  .uni-input {
    color: #000;
  }

  .uni-select-box {
    padding-left: 2rpx !important;
  }
</style>